package cn.controller;

import cn.common.ExceResult;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.common.PageString;
import cn.filter.LoginCheck;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.teamassessment.*;
import cn.kpi.entity.usualassessment.OrgTitle;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.teamassement.IBUAssTemplateService;
import cn.kpi.service.teamassement.IBUKPIService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.*;

import static javax.print.attribute.standard.MediaSizeName.A;

@Controller
@RequestMapping("teamass")
public class TeamAssessController extends BaseController {

    @Autowired
    private IBUAssTemplateService ibuAssTemplateService;

    @Autowired
    private IBUKPIService ibukpiService;


    @Autowired
    private IOrgService orgService;

    //region 指标部分
    @RequestMapping(value = "/index_list")
    public String IndexList(Model model) {
        return "teamassment/buns_index_list";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_index_list")
    public GridCommon<BUAssTempCreateIndexEntity> GetIndexList(HttpServletRequest request) {
        List<BUAssTempCreateIndexEntity> lst = null;
        GridCommon<BUAssTempCreateIndexEntity> countlist = new GridCommon<BUAssTempCreateIndexEntity>();
        try {

            String where = "";
            lst = ibuAssTemplateService.GetIndexListByWhere(where);

            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");

        } catch (Exception e) {
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return countlist;
    }

    @RequestMapping(value = "/buns_kp_look")
    public String kpLook(Model model) {
        Long templateid = Long.parseLong("15");
        try {
            List<BUAssTempCreateIndexEntity> lstdetail = ibuAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";

            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
            }
            columns = columns.substring(0, columns.length() - 1);

            List<Map> lstorg = ibukpiService.GetBUKPIMapByTempIdAndColumns(templateid, columns);

            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);


        } catch (Exception e) {

        }

        return "teamassment/buns_kp_look";


    }

    @RequestMapping(value = "/export")
    public String export(Model model, Long templateid, String str) {
        String type = "m";
        String[] strs = str.split(",");
        List<BUAssTemplateEntity> lstdetails = new ArrayList<>();
        try {
            List<BUAssTemplateEntity> list = ibuAssTemplateService.GetUsAssTemplateListByWhere(" and  templateid=" + templateid);
            String remark = "";
            if (list.size() > 0) {

                remark = list.get(0).getTemplatedes();
            }


            model.addAttribute("remark", remark);

            String year = "";
            String quarter = "";
            year = strs[0];
            if (strs.length > 2) {

                if (strs[2].equals("m")) {
                    model.addAttribute("date", strs[0] + "年" + strs[1] + "月");
                } else if (strs[2].equals("q")) {
                    model.addAttribute("date", strs[0] + "年" + strs[1] + "季度");
                    type = "q";
                    quarter = strs[1];

                }else{
                    model.addAttribute("date", strs[0] + "年");
                    type = "y";
                }
            } else {
                model.addAttribute("date", strs[0] + "年");
                type = "y";

            }


            List<String> dates = new ArrayList<>();

            if (type == "y") {

                for (int i = 1; i < 13; i++) {

                    String text = i + "";
                    if (i < 9) text = "0" + i;
                    dates.add(year + "-" + text + "-01");
                }

            } else if (type == "m") {

                List<BUAssTempCreateIndexEntity> lstdetail = ibuAssTemplateService.GetTemplateIndexBytemplateid(templateid);
                String columns = "";

                for (int i = 0; i < lstdetail.size(); i++) {
                    columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                }
                columns = columns.substring(0, columns.length() - 1);

                List<Map> lstorg = ibukpiService.GetBUKPIMapByTempIdAndColumns(templateid, columns);


                HashMap<String, String> hs = new HashMap<>();


                for (int i = 0; i < lstorg.size(); i++) {


                    if (!hs.containsKey(lstorg.get(i).get("sumscore"))) {


                        hs.put(lstorg.get(i).get("sumscore").toString(), "");

                    }
                }
                float[] descArray = new float[hs.size()];


                int index = 0;
                for (String key : hs.keySet()) {
                    descArray[index] = Float.parseFloat(key);
                    index++;

                }

                Arrays.sort(descArray);
                int orderIndex = 0;
                for (int i = descArray.length - 1; i >= 0; i--) {
                    orderIndex++;
                    for (int j = 0; j < lstorg.size(); j++) {
                        if (descArray[i] == Float.parseFloat(lstorg.get(j).get("sumscore").toString())) {

                            lstorg.get(j).put("orderindex", orderIndex);

                        }

                    }

                }


                model.addAttribute("titleh", lstdetail);
                model.addAttribute("databody", lstorg);

            } else {

                dates = getDateByQuarter(year, quarter);
            }
            if (type != "m") {


                for (int i = 0; i < dates.size(); i++) {

                    String where = dates.get(i);
                    List<BUAssTemplateEntity> sub = ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(where));
                    if (sub.size() > 0) {
                        lstdetails.addAll(sub);
                    }

                }
                String itemids = "";
                for (int i = 0; i < lstdetails.size(); i++) {

                    if (itemids == "") {
                        itemids = lstdetails.get(i).getTemplateid() + "";

                    } else {
                        itemids += "," + lstdetails.get(i).getTemplateid() + "";

                    }
                }
                int divisor = 3;
                if (type.equals("y")) divisor = 12;
                List<Map> lstorg = ibukpiService.GetBUKPIMapByTempId(itemids, divisor);


                HashMap<String, String> hs = new HashMap<>();


                for (int i = 0; i < lstorg.size(); i++) {


                    if (!hs.containsKey(lstorg.get(i).get("sumscore"))) {


                        hs.put(lstorg.get(i).get("sumscore").toString(), "");

                    }
                }
                float[] descArray = new float[hs.size()];


                int index = 0;
                for (String key : hs.keySet()) {
                    descArray[index] = Float.parseFloat(key);
                    index++;

                }

                Arrays.sort(descArray);
                int orderIndex = 0;
                for (int i = descArray.length - 1; i >= 0; i--) {
                    orderIndex++;
                    for (int j = 0; j < lstorg.size(); j++) {
                        if (descArray[i] == Float.parseFloat(lstorg.get(j).get("sumscore").toString())) {

                            lstorg.get(j).put("orderindex", orderIndex);

                        }

                    }

                }


                model.addAttribute("databody", lstorg);
            }


        } catch (Exception e) {

        }


        List<Map> list = ibuAssTemplateService.getTitle(templateid, "t",str);
        String title = "";
        if (list.size() > 0) {
            title = list.get(0).get("title").toString();
        }
        model.addAttribute("title", title);
        if (type == "m") {
            return "teamassment/buns_kp_export";
        } else {
            return "teamassment/buns_kp_exportYear";

        }


    }


    @RequestMapping(value = "/look")
    public String look(Model model, Long templateid, String str) {
        String type = "m";
        List<BUAssTemplateEntity> lstdetails = new ArrayList<>();
        try {
            List<BUAssTemplateEntity> list = ibuAssTemplateService.GetUsAssTemplateListByWhere(" and  templateid=" + templateid);
            String remark = "";
            if (list.size() > 0) {

                remark = list.get(0).getTemplatedes();
            }


            model.addAttribute("remark", remark);
            String[] strs = str.split(",");
            String year = "";
            String quarter = "";
            year = strs[0];
            if (strs.length > 2) {

                if (strs[2].equals("m")) {
                    model.addAttribute("date", strs[0] + "年" + strs[1] + "月");
                } else if (strs[2].equals("q")) {
                    model.addAttribute("date", strs[0] + "年" + strs[1] + "季度");
                    type = "q";
                    quarter = strs[1];

                }else{
                    model.addAttribute("date", strs[0] + "年");
                    type = "y";
                }
            } else {
                model.addAttribute("date", strs[0] + "年");
                type = "y";

            }


            List<String> dates = new ArrayList<>();

            if (type == "y") {

                for (int i = 1; i < 13; i++) {

                    String text = i + "";
                    if (i < 9) text = "0" + i;
                    dates.add(year + "-" + text + "-01");
                }

            } else if (type == "m") {

                List<BUAssTempCreateIndexEntity> lstdetail = ibuAssTemplateService.GetTemplateIndexBytemplateid(templateid);
                String columns = "";

                for (int i = 0; i < lstdetail.size(); i++) {
                    columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
                }
                columns = columns.substring(0, columns.length() - 1);

                List<Map> lstorg = ibukpiService.GetBUKPIMapByTempIdAndColumns(templateid, columns);

                System.out.println(JSON.toJSONString(lstorg));


                model.addAttribute("titleh", lstdetail);
                model.addAttribute("databody", lstorg);

            } else {

                dates = getDateByQuarter(year, quarter);
            }
            if (type != "m") {


                for (int i = 0; i < dates.size(); i++) {

                    String where = dates.get(i);
                    List<BUAssTemplateEntity> sub = ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(where));
                    if (sub.size() > 0) {
                        lstdetails.addAll(sub);
                    }

                }
                String itemids = "";
                for (int i = 0; i < lstdetails.size(); i++) {

                    if (itemids == "") {
                        itemids = lstdetails.get(i).getTemplateid() + "";

                    } else {
                        itemids += "," + lstdetails.get(i).getTemplateid() + "";

                    }
                }
                int divisor = 3;
                if (type.equals("y")) divisor = 12;
                List<Map> lstorg = ibukpiService.GetBUKPIMapByTempId(itemids, divisor);
                model.addAttribute("databody", lstorg);
            }


        } catch (Exception e) {

        }


        if (type == "m") {
            return "teamassment/look";
        } else {
            return "teamassment/look1";

        }


    }


    private List<String> getDateByQuarter(String year, String quarter) {

        List<String> dates = new ArrayList<>();
        if (quarter.equals("1")) {
            dates.add((year + "-01-01"));
            dates.add((year + "-02-01"));
            dates.add((year + "-03-01"));


        } else if (quarter.equals("2")) {
            dates.add((year + "-04-01"));
            dates.add((year + "-05-01"));
            dates.add((year + "-06-01"));


        } else if (quarter.equals("3")) {

            dates.add((year + "-07-01"));
            dates.add((year + "-08-01"));
            dates.add((year + "-09-01"));
        } else {
            dates.add((year + "-10-01"));
            dates.add((year + "-11-01"));
            dates.add((year + "-12-01"));

        }

        return dates;
    }


    @RequestMapping(value = "/index_edit")
    public String IndexEdit(Model model, Long assindexid) {
        try {
            String where = " AND assindextype=0";
            List<BUAssTemplateIndexEntity> lst = ibuAssTemplateService.GetTemplateIndexListByWhere(where);
            model.addAttribute("lst", lst);
            BUAssTemplateIndexEntity entity = new BUAssTemplateIndexEntity();
            if (assindexid > 0) {
                entity = ibuAssTemplateService.GetIndexById(assindexid);
            }
            model.addAttribute("entity", entity);

        } catch (Exception ex) {

        }
        return "teamassment/buns_index_edit";
    }

    @ResponseBody
    @RequestMapping(value = "/add_title")
    public String addTitle(HttpServletRequest request, HttpServletResponse response) {


        try {

            String title = request.getParameter("title");
            Long templateId=0L;
            if(request.getParameter("templateId")!=""){
                templateId  = Long.valueOf(request.getParameter("templateId"));
              }
              // if(templateId==0)return "";

            String str = request.getParameter("str");
            String[] strings = str.split(",");
            String addType=strings[2];
            OrgTitle orgTitle = new OrgTitle();
            String type = "t";
            orgTitle.setTitle(title);
            orgTitle.setSection(str);
            orgTitle.setType(type);
            orgTitle.setTemplateId(templateId);
            ibuAssTemplateService.addTitle(orgTitle,addType=="m"?"":addType);

        } catch (Exception ex) {


        }
        return "";
    }

    @ResponseBody
    @RequestMapping(value = "/get_title")
    public List<Map> getTitle(HttpServletRequest request, HttpServletResponse response) {


        try {


            Long templateId = Long.valueOf(request.getParameter("templateId"));

             String str=request.getParameter("str");

            return ibuAssTemplateService.getTitle(templateId, "t",str);

        } catch (Exception ex) {


        }
        return null;
    }


    @RequestMapping(value = "/add_templateindex")
    public String AddTemplateindex(HttpServletRequest request, HttpServletResponse response) {
        try {
            BUAssTemplateIndexEntity entity = new BUAssTemplateIndexEntity();
            if (request.getParameter("assindexid") == null || request.getParameter("assindexid").equals("")) {
                entity.setAssindexid(0L);
            } else {
                entity.setAssindexid(Long.parseLong(request.getParameter("assindexid")));
            }

            entity.setAssindextype(Integer.parseInt(request.getParameter("assindextype")));
            entity.setByuserid(this.GetLoginUserId());
            entity.setParentid(Long.valueOf(request.getParameter("parentid")));
            entity.setScore(Integer.parseInt(request.getParameter("score")));
            entity.setTemplateid(Long.valueOf(0));
            if (entity.getAssindextype() == 1) {
                entity.setUassingredients(request.getParameter("uasscontent").trim());
                entity.setEvaluationstandard(request.getParameter("evaluationstandard").trim());
            } else {
                entity.setUasscontent(request.getParameter("uasscontent").trim());
            }

            int iResult = 0;
            if (entity.getAssindexid() > 0) {
                iResult = ibuAssTemplateService.UpdateIndex(entity);
            } else {
                if (entity.getParentid() == 0) {
                    entity.setScore(0);
                }
                iResult = ibuAssTemplateService.InsertTemplateIndexentity(entity);
            }


            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete_index")
    public ExceResult DeleteIndex(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long assindexid = Long.parseLong(request.getParameter("assindexid"));
            Long parentid = Long.parseLong(request.getParameter("parentid"));
            int iResult = ibuAssTemplateService.DeleteIndex(assindexid, parentid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }
    //endregion

    //region 指标模版部分
    @RequestMapping(value = "/template_list_alone")
    public String TemplateListAlone(Model model) {
        return "teamassment/buns_template_list_alone";
    }

    @RequestMapping(value = "/template_list_alone_edit")
    public String TemplateListAloneEdit(Model model, Long templateid) {
        try {
            List<BUAssTemplateIndexEntity> lst = ibuAssTemplateService.GetTemplateIndexListRowSpanByTempId(templateid);
            model.addAttribute("lst", lst);
            model.addAttribute("templateid", templateid);

            String parentid = "";
            String usassid = "";
            for (int i = 0; i < lst.size(); i++) {
                BUAssTemplateIndexEntity entity = lst.get(i);
                usassid += entity.getAssindexid().toString() + ",";
                if (parentid.length() > 0) {
                    String[] strarr = parentid.split(",");
                    String last = strarr[strarr.length - 1];
                    if (!last.equals(entity.getParentid().toString())) {
                        parentid += entity.getParentid().toString() + ",";
                    }
                } else {
                    parentid += entity.getParentid().toString() + ",";
                }

            }
            PageString pagestring = new PageString();
            pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
            pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
            model.addAttribute("pagestring", pagestring);

            if (templateid > 0) {
                BUAssTemplateEntity ustempentity = ibuAssTemplateService.GetUsAssTemplateListById(templateid);
                model.addAttribute("ustempentity", ustempentity);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "teamassment/buns_template_list_alone_edit";
    }

    @RequestMapping(value = "/create_templateindex")
    public String CreateTemplateIndex(HttpServletRequest request, HttpServletResponse response) {
        try {
            String strtemplateid = request.getParameter("templateid");
            Long templateid = Long.parseLong(strtemplateid);


            String parentids = request.getParameter("parentids");
            String assindexids = request.getParameter("assindexids");

            String[] parentidsArr = parentids.split(",");
            String[] assindexidsArr = assindexids.split(",");

            Long flag = 0L;
            List<BUAssTempCreateIndexEntity> lst = new ArrayList<BUAssTempCreateIndexEntity>();

            Long byuserid = this.GetLoginUserId();
            for (int i = 0; i < assindexidsArr.length; i++) {
                if (request.getParameter("cb_" + assindexidsArr[i]) != null) {
                    BUAssTempCreateIndexEntity entity = new BUAssTempCreateIndexEntity();
                    entity.setAssindexid(Long.parseLong(assindexidsArr[i]));
                    entity.setAssindextype(1);
                    entity.setParentid(Long.parseLong(request.getParameter("parentid_" + assindexidsArr[i])));
                    entity.setTemplateid(templateid);
                    entity.setEvaluationstandard(request.getParameter("evaluationstandard_" + assindexidsArr[i]));
                    entity.setScore(Integer.parseInt(request.getParameter("score_" + assindexidsArr[i])));
                    entity.setUassingredients(request.getParameter("uassingredients_" + assindexidsArr[i]));
                    entity.setUasscontent(request.getParameter("uasscontent_" + entity.getParentid()));
                    entity.setByuserid(byuserid);
                    lst.add(entity);
                }
            }

            if (lst.size() <= 0) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'请选择指标项')</script>");
            }
            String assindexidScore = "";
            for (int i = 0; i < lst.size(); i++) {

                if (assindexidScore == "") {
                    assindexidScore += lst.get(i).getAssindexid().toString();

                } else {

                    assindexidScore += "," + lst.get(i).getAssindexid();
                }

            }
            assindexidScore += "";
            int sumScore = 0;
            List<BUAssTemplateIndexEntity> list = ibuAssTemplateService.GetTemplateIndexListByWhere(" and  assindexid  in (" + assindexidScore + ")");
            for (int i = 0; i < list.size(); i++) {

                sumScore += list.get(i).getScore();
            }

            if (sumScore > 100) {
                return renderStringScript(response, "<script>window.parent.CloseDialog(0,'总分不能超过100分')</script>");

            }
            BUAssTemplateEntity tempentity = new BUAssTemplateEntity();

            tempentity.setTemplatename(request.getParameter("templatename"));
            tempentity.setBegintime(Date.valueOf(request.getParameter("begintime") + "-01"));
//            tempentity.setEndtime(Date.valueOf(request.getParameter("endtime")));
            tempentity.setTemplatedes(request.getParameter("templatedes"));
            tempentity.setByuserid(byuserid);
            int iResult = 0;
            if (templateid > 0) {
                tempentity.setTemplateid(templateid);
                iResult = ibuAssTemplateService.UpdateUsAssTempEntity(lst, tempentity);
            } else {
                iResult = ibuAssTemplateService.CreateTemplateAndIndex(lst, tempentity);
            }
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    //部门应用模板
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<BUAssTemplateEntity> GetList(HttpServletRequest request) {

        List<BUAssTemplateEntity> lst = null;
        LayTable<BUAssTemplateEntity> layTable = new LayTable<BUAssTemplateEntity>();
        try {
            String templatename = request.getParameter("templatename");

            String where = "";
            if (templatename != null && templatename.length() > 0) {
                where += " AND templatename LIKE '%" + templatename.trim() + "%'";
            }

            lst = ibuAssTemplateService.GetUsAssTemplateListByWhere(where);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = ibuAssTemplateService.GetUsAssTemplateListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_template")
    public ExceResult DeleteTemplate(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            int iResult = ibuAssTemplateService.DeleteUsTempEntity(templateid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @RequestMapping(value = "/buns_templae_list_org_edit")
    public String templateOrgEdit(Model model, Long templateid) {
        try {
            List<BUAssTemplateOrgEntity> lst = ibuAssTemplateService.GetTempOrgListByTempId(templateid);
            model.addAttribute("lst", lst);
            model.addAttribute("templateid", templateid);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "teamassment/buns_templae_list_org_edit";
    }


    @ResponseBody
    @RequestMapping(value = "/get_CheckorgList")
    public List<BUAssTemplateOrgEntity> getCheckOrgList(HttpServletRequest request, HttpServletResponse response) {
        List<BUAssTemplateOrgEntity> lst = new ArrayList<>();
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));
            lst = ibuAssTemplateService.GetTempOrgListByTempId(templateid);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return lst;
    }


    @ResponseBody
    @RequestMapping(value = "/get_orgList")
    public GridCommon<OrgEntity> getOrgList(HttpServletRequest request, HttpServletResponse response) {
        List<OrgEntity> list = new ArrayList<>();
        GridCommon<OrgEntity> rs = new GridCommon<>();
        try {


            list = orgService.GetOrgListByWhere("  and orgtype=0  ");
            rs.setCountRecord(list.size());
            rs.setItems(list);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return rs;
    }


    @ResponseBody
    @RequestMapping(value = "/create_templateorg")
    public ExceResult CreateTemplateOrg(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String orgid = request.getParameter("origid");
            Long templateidl = Long.parseLong(request.getParameter("templateid"));

            String[] oridArr = orgid.split(",");

            Long byuserid = this.GetLoginUserId();//未使用

            List<Long> orgList = new ArrayList<>();
            for (String s : oridArr) {
                orgList.add(Long.valueOf(s));
            }
            int iResult = ibuAssTemplateService.InsertBuTempOrgBatch(templateidl, orgList);

            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //endregion

    //region 指标打分部分
    @RequestMapping(value = "/buns_kp_list")
    public String kpiListView(Model model) {
        return "teamassment/buns_kp_list";
    }

    //模板
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_kpi_list")
    public LayTable<BUAssTemplateEntity> GetkpiList(HttpServletRequest request) {

        List<BUAssTemplateEntity> lst = null;
        LayTable<BUAssTemplateEntity> layTable = new LayTable<BUAssTemplateEntity>();
        try {
            String templatename = request.getParameter("templatename");

            String where = "";
            if (templatename != null && templatename.length() > 0) {
                where += " AND kpiname LIKE '%" + templatename.trim() + "%'";
            }

            lst = ibuAssTemplateService.GetUsAssTemplateListByWhere(where);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = ibuAssTemplateService.GetUsAssTemplateListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @RequestMapping(value = "/buns_kp_read")
    public String kpiread(Model model, Long templateid) {
        try {
            List<BUAssTempCreateIndexEntity> lstdetail = ibuAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";

            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
            }
            columns = columns.substring(0, columns.length() - 1);

            List<Map> lstorg = ibukpiService.GetBUKPIMapByTempIdAndColumns(templateid, columns);

            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", lstorg);


        } catch (Exception e) {

        }
        return "teamassment/" +
                "" +
                "" +
                "" +
                "" +
                "" +
                "" +
                "" +
                "" +
                "" +
                "";
    }

    @RequestMapping(value = "/buns_kp_edit")
    public String kpiedit(Model model, Long templateid) {
        try {
            List<BUAssTempCreateIndexEntity> lstdetail = ibuAssTemplateService.GetTemplateIndexBytemplateid(templateid);
            String columns = "";
            for (int i = 0; i < lstdetail.size(); i++) {
                columns += "MAX(CASE WHEN assindexid='" + lstdetail.get(i).getAssindexid() + "' THEN score ELSE 0 END) AS '" + lstdetail.get(i).getAssindexid() + "',";
            }
            columns = columns.substring(0, columns.length() - 1);
            //实际数据
            List<Map> lstorg = ibukpiService.GetBUKPIMapByTempIdAndColumns(templateid, columns);
            //应该有的岗位数据
            List<BUAssTemplateOrgEntity> buAssTemplateOrgEntities = ibuAssTemplateService.GetChooseOrgListByTempId(templateid);
            List<Map> newMaps = new ArrayList<>();
            //数据合并
            for (BUAssTemplateOrgEntity buAssTemplateOrgEntity : buAssTemplateOrgEntities) {
                boolean isContent = false;
                long orgid = buAssTemplateOrgEntity.getOrgid();
                for (Map map : lstorg) {//是否已经有值
                    if (map.get("orgid") == orgid) {
                        isContent = true;
                        newMaps.add(map);
                    }
                }
                if (!isContent) {//初始化数据
                    Map mape = new HashMap();
                    mape.put("orgid", orgid);
                    mape.put("orgname", buAssTemplateOrgEntity.getOrgname());
                    mape.put("templateid", templateid);
                    for (BUAssTempCreateIndexEntity indexEntity : lstdetail) {
                        mape.put(indexEntity.getAssindexidcolum(), ibuAssTemplateService.GetIndexById(indexEntity.getAssindexid()).getScore());
                    }
                    newMaps.add(mape);
                }
            }

//            lstorg.addAll(newMaps);

            System.out.println(JSON.toJSONString(lstorg));

            model.addAttribute("titleh", lstdetail);
            model.addAttribute("databody", newMaps);
            model.addAttribute("templateid", templateid);


        } catch (Exception e) {

        }
        return "teamassment/buns_kp_edit";
    }

    @RequestMapping(value = "/create_kpiscore")
    public String CreateKpiScore(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<BUKPItemEntity> bukpItemEntities = new ArrayList<>();
            //获取所有的值
            Map<String, String> map = new HashMap<>();
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                String value = request.getParameter(name);
                map.put(name, value);
            }
            Long templateId = Long.valueOf(map.get("templateid"));
            for (String key : map.keySet()) {
                if (!key.equals("templateid")) {
                    String[] indexs = key.split("_");
                    BUKPItemEntity bukpItemEntity = new BUKPItemEntity();
                    bukpItemEntity.setTemplateid(templateId);
                    bukpItemEntity.setOrgid(Long.valueOf(indexs[1]));
                    bukpItemEntity.setAssindexid(Long.valueOf(indexs[2]));
                    if (map.get(key) != null && map.get(key).trim() != "") {

                        BigDecimal score = new BigDecimal(map.get(key));

                        bukpItemEntity.setScore(score);
                        bukpItemEntity.setComplete(1);

                    } else {
                        bukpItemEntity.setScore(new BigDecimal("0"));
                        bukpItemEntity.setComplete(0);

                    }


                    bukpItemEntities.add(bukpItemEntity);
                }
            }
            int iResult = ibukpiService.InsertBUKPItemBatch(templateId, bukpItemEntities);
//            if (iResult > 0) {
//
//                ibuAssTemplateService.updateSubmit(templateId, 1);
//
//            }


            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/submit")
    public ExceResult submit(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long templateid = Long.parseLong(request.getParameter("templateid"));

            int iResult = ibuAssTemplateService.updateSubmit(templateid, 1);
            result.setCode(200);
            result.setResult(iResult);
            result.setMsg("操作成功");
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/gettemplatebybegin")
    public LayTable<BUAssTemplateEntity> gettemplatebybegin(HttpServletRequest request, HttpServletResponse response) {
        LayTable<BUAssTemplateEntity> layTable = new LayTable<BUAssTemplateEntity>();
        try {
            String begintime = request.getParameter("begintime");

            List<BUAssTemplateEntity> lstdetail = ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(begintime + "-01"));
            layTable.setData(lstdetail);
        } catch (Exception ex) {

        }
        return layTable;
    }


    @ResponseBody
    @RequestMapping(value = "/gettemplatebyquarter")
    public LayTable<BUAssTemplateEntity> gettemplatebyAuqrter(HttpServletRequest request, HttpServletResponse response) {
        LayTable<BUAssTemplateEntity> layTable = new LayTable<BUAssTemplateEntity>();
        try {
            String year = request.getParameter("year");
            String quarter = request.getParameter("quarter");
            List<BUAssTemplateEntity> lstdetail = new ArrayList<>();
            if (quarter.equals("1")) {

                for (int i = 1; i < 4; i++) {
                    lstdetail.addAll(ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(year + "-" + i + "-01")));
                }
            } else if (quarter.equals("2")) {

                for (int i = 4; i < 7; i++) {
                    lstdetail.addAll(ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(year + "-" + i + "-01")));
                }

            } else if (quarter.equals("3")) {

                for (int i = 7; i < 10; i++) {
                    lstdetail.addAll(ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(year + "-" + i + "-01")));
                }
            } else {
                for (int i = 10; i < 13; i++) {
                    lstdetail.addAll(ibuAssTemplateService.getTemplateByBeginTime(Date.valueOf(year + "-" + i + "-01")));
                }
            }


            layTable.setData(lstdetail);
        } catch (Exception ex) {

        }
        return layTable;
    }

    //endregion
}
